package com.hmyuan.controller.front;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hmyuan.domain.Category;
import com.hmyuan.domain.Comment;
import com.hmyuan.service.CommentService;
import com.hmyuan.util.RequestMessageUtil;
import com.hmyuan.util.images.ValidateCode;
/**
 * 评论Controler
 * @author suxiaofei
 *
 */
@Controller
@RequestMapping("/comment")
public class FrontCommentController {
	@Resource
	CommentService commentService;
	/**
	 * 查询评论列表
	 */
	@RequestMapping("/findcommentListByArticleid/{articleid}")
	public String findcategoryList(HttpServletRequest request,Model model,@PathVariable Long articleid){
		if(articleid==null) return null;
		request.setAttribute("commentList", commentService.selectListByArticleid(articleid));
		return "/comment/commentList";
	}
	/**
	 *添加评论 
	 */
	@ResponseBody
	@RequestMapping("/categoryAddPage")
	public Map<String, Object> categoryAddPage(HttpServletRequest request,Model model,
			Comment comment,
			String validateCode
			){
		
		Map<String, Object> result = new HashMap<String, Object>();
		
		HttpSession session = request.getSession();
		String vaCode = (String) session.getAttribute("code");
		
		if(vaCode==null||validateCode==null||!vaCode.equals(validateCode.toUpperCase())){
			result.put("code", 2);
			result.put("massage", "验证码错误！");
		}else{
			if(comment.getParentid()==null){
				comment.setParentid(0l);
			}
			
			comment.setCreatetime(new Date());
			comment.setStaus(0);
			comment.setIp(RequestMessageUtil.getIpAddress(request));
			comment.setOs(RequestMessageUtil.getOs(request));
			comment.setBrowser(RequestMessageUtil.getBrowserInfo(request));
			commentService.insert(comment);
			
			//给根评论设置rootid
			if(comment.getParentid()==0){
				Comment c2 = new Comment();
				c2.setId(comment.getId());
				c2.setRootid(comment.getId());
				commentService.updateByPrimaryKeySelective(c2);
				comment.setRootid(c2.getRootid());
			}
			
			result.put("code", 0);
			result.put("massage", "评论成功！");
			result.put("comment", comment);
		}
		
		
		return result;
	}
}
